package xdpm.nhom16.GUI;

import java.io.IOException;
import java.util.ArrayList;

import xdpm.nhom16.R;
import xdpm.nhom16.BUS.DataProvider;
import xdpm.nhom16.BUS.SearchEngine;
import xdpm.nhom16.DAO.MySQLiteHelper;
import xdpm.nhom16.helper.Utilities;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.ImageButton;
import android.widget.MultiAutoCompleteTextView;
import android.widget.MultiAutoCompleteTextView.Tokenizer;
import android.widget.Toast;

public class DichVuHCMActivity extends CustomWindow
{
	private DichVuHCMActivity thisActivity;
	private Thread downloaderThread;
	private ProgressDialog progressDialog;
	private AutoCompleteTextView txtHomeSearch;
	private ImageButton btnDanhSachKetQua;

	// Used to communicate state changes in the DownloaderThread
	public static final int MESSAGE_DOWNLOAD_STARTED = 1000;
	public static final int MESSAGE_DOWNLOAD_COMPLETE = 1001;
	public static final int MESSAGE_UPDATE_PROGRESS_BAR = 1002;
	public static final int MESSAGE_DOWNLOAD_CANCELED = 1003;
	public static final int MESSAGE_CONNECTING_STARTED = 1004;
	public static final int MESSAGE_ENCOUNTERED_ERROR = 1005;
	
	private static ArrayList<String> listTenDichVu = new ArrayList<String>();
	private static ArrayList<String> listTenDuong = new ArrayList<String>();
	public static ArrayList<String> listDichVuDuong = new ArrayList<String>();
	public static ArrayList<String> listDuong = new ArrayList<String>();
	
	private String str;

	public String getStr() {
		return str;
	}
	public void setStr(String str) {
		this.str = str;
	}
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		DataProvider.getInstance(this);
		
		thisActivity = this;
		downloaderThread = null;
		progressDialog = null;

		SearchEngine engine = new SearchEngine(DataProvider.getContext());
		
		listTenDichVu = engine.getTenDichVu();
		listTenDuong = engine.getTenDuong();
		
		for (int i = 0; i < listTenDichVu.size(); i++){
			listDichVuDuong.add(Utilities.formatInputData(listTenDichVu.get(i)));
		}
		

		for (int i = 0; i < listTenDuong.size(); i++){
			listDuong.add(Utilities.formatInputData(listTenDuong.get(i)));
		}
		
		
		txtHomeSearch = (AutoCompleteTextView) findViewById(R.id.autocomplete);
		Autocomplete auto = new Autocomplete(txtHomeSearch, engine, this);
		auto.test();
		
		txtHomeSearch.setOnKeyListener(new OnKeyListener() {
			public boolean onKey(View v, int keyCode, KeyEvent event)
			{
				if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT || keyCode == KeyEvent.KEYCODE_DPAD_UP || keyCode == KeyEvent.KEYCODE_DPAD_DOWN
						|| keyCode == KeyEvent.KEYCODE_ENTER)
				{
					InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
					imm.hideSoftInputFromWindow(txtHomeSearch.getApplicationWindowToken(), 0);
				}

				return false;
			}
		});

		btnDanhSachKetQua = (ImageButton) findViewById(R.id.btn_home_search);

		btnDanhSachKetQua.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v)
			{
				onClickHomeSearch();
			}
		});	
	}
	public void onClickHomeSearch()	{
		Utilities.onClickButtonSearch(txtHomeSearch.getText().toString(), this);
	}
	
	public void onSetting(View v)
	{
		startActivity(new Intent(this, ThietLapForm.class));
	}
	
	public void onAbout(View v)
	{
		AlertDialog.Builder alertDialog = new Builder(this);
		alertDialog.create();
		alertDialog.setTitle("Giới thiệu");
		alertDialog.setIcon(R.drawable.about);

		final View aboutView = getLayoutInflater().inflate(R.layout.about, null);

		alertDialog.setView(aboutView);
		alertDialog.setPositiveButton("Đóng", new OnClickListener() {
			public void onClick(DialogInterface dialog, int which)
			{
			}
		});

		alertDialog.show();
	}

	public void onUpdate(View v)
	{
		AlertDialog.Builder alertDialog = new Builder(this);
		alertDialog.create();
		alertDialog.setTitle("Thông báo");
		alertDialog.setIcon(R.drawable.update);
		alertDialog.setMessage("Nâng cấp phần mềm ?");

		alertDialog.setPositiveButton("Có", new AlertDialog.OnClickListener() {
			public void onClick(DialogInterface dialog, int which)
			{
				downloaderThread = new DownloaderThread(thisActivity, "http://ntruths.com/xdpm/DanhSachDichVu");
				downloaderThread.start();
			}
		});

		alertDialog.setNegativeButton("Không", null);
		alertDialog.show();
	}

	public Handler activityHandler = new Handler() {
		public void handleMessage(Message msg)
		{
			switch (msg.what)
			{
			/*
			 * Handling MESSAGE_UPDATE_PROGRESS_BAR: 1. Get the current progress, as indicated in the arg1 field of the Message. 2. Update the progress bar.
			 */
			case MESSAGE_UPDATE_PROGRESS_BAR:
				if (progressDialog != null)
				{
					int currentProgress = msg.arg1;
					progressDialog.setProgress(currentProgress);
				}
				break;

			/*
			 * Handling MESSAGE_CONNECTING_STARTED: 1. Get the URL of the file being downloaded. This is stored in the obj field of the Message. 2. Create an indeterminate progress bar. 3. Set the
			 * message that should be sent if user cancels. 4. Show the progress bar.
			 */
			case MESSAGE_CONNECTING_STARTED:
				if (msg.obj != null && msg.obj instanceof String)
				{
					String url = (String) msg.obj;
					// truncate the url
					if (url.length() > 16)
					{
						String tUrl = url.substring(0, 15);
						tUrl += "...";
						url = tUrl;
					}
					String pdTitle = thisActivity.getString(R.string.progress_dialog_title_connecting);
					String pdMsg = thisActivity.getString(R.string.progress_dialog_message_prefix_connecting);
					pdMsg += " " + url;

					dismissCurrentProgressDialog();
					progressDialog = new ProgressDialog(thisActivity);
					progressDialog.setIcon(R.drawable.update);
					progressDialog.setTitle(pdTitle);
					progressDialog.setMessage(pdMsg);
					progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
					progressDialog.setIndeterminate(true);
					// set the message to be sent when this dialog is canceled
					Message newMsg = Message.obtain(this, MESSAGE_DOWNLOAD_CANCELED);
					progressDialog.setCancelMessage(newMsg);
					progressDialog.show();
				}
				break;

			/*
			 * Handling MESSAGE_DOWNLOAD_STARTED: 1. Create a progress bar with specified max value and current value 0; assign it to progressDialog. The arg1 field will contain the max value. 2. Set
			 * the title and text for the progress bar. The obj field of the Message will contain a String that represents the name of the file being downloaded. 3. Set the message that should be sent
			 * if dialog is canceled. 4. Make the progress bar visible.
			 */
			case MESSAGE_DOWNLOAD_STARTED:
				// obj will contain a String representing the file name
				if (msg.obj != null && msg.obj instanceof String)
				{
					int maxValue = msg.arg1;
					String fileName = (String) msg.obj;
					String pdTitle = thisActivity.getString(R.string.progress_dialog_title_downloading);
					String pdMsg = thisActivity.getString(R.string.progress_dialog_message_prefix_downloading);

					pdMsg += " " + fileName;

					dismissCurrentProgressDialog();
					progressDialog = new ProgressDialog(thisActivity);
					progressDialog.setTitle(pdTitle);
					progressDialog.setIcon(R.drawable.update);
					progressDialog.setMessage(pdMsg);
					progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
					progressDialog.setProgress(0);
					progressDialog.setMax(maxValue);
					// set the message to be sent when this dialog is canceled
					Message newMsg = Message.obtain(this, MESSAGE_DOWNLOAD_CANCELED);
					progressDialog.setCancelMessage(newMsg);
					progressDialog.setCancelable(true);
					progressDialog.show();
				}
				break;

			/*
			 * Handling MESSAGE_DOWNLOAD_COMPLETE: 1. Remove the progress bar from the screen. 2. Display Toast that says download is complete.
			 */
			case MESSAGE_DOWNLOAD_COMPLETE:
				dismissCurrentProgressDialog();
				displayMessage(getString(R.string.user_message_download_complete));
				break;

			/*
			 * Handling MESSAGE_DOWNLOAD_CANCELLED: 1. Interrupt the downloader thread. 2. Remove the progress bar from the screen. 3. Display Toast that says download is complete.
			 */
			case MESSAGE_DOWNLOAD_CANCELED:
				if (downloaderThread != null)
				{
					downloaderThread.interrupt();
				}
				dismissCurrentProgressDialog();
				displayMessage(getString(R.string.user_message_download_canceled));
				break;

			/*
			 * Handling MESSAGE_ENCOUNTERED_ERROR: 1. Check the obj field of the message for the actual error message that will be displayed to the user. 2. Remove any progress bars from the screen.
			 * 3. Display a Toast with the error message.
			 */
			case MESSAGE_ENCOUNTERED_ERROR:
				// obj will contain a string representing the error message
				if (msg.obj != null && msg.obj instanceof String)
				{
					String errorMessage = (String) msg.obj;
					dismissCurrentProgressDialog();
					displayMessage(errorMessage);
				}
				break;

			default:
				// nothing to do here
				break;
			}
		}
	};

	public void dismissCurrentProgressDialog()
	{
		if (progressDialog != null)
		{
			progressDialog.hide();
			progressDialog.dismiss();
			progressDialog = null;
		}
	}

	/**
	 * Displays a message to the user, in the form of a Toast.
	 * 
	 * @param message
	 *            Message to be displayed.
	 */
	public void displayMessage(String message)
	{
		if (message != null)
		{
			Toast.makeText(thisActivity, message, Toast.LENGTH_SHORT).show();
		}
	}

	public void setupAutocompleteTextView(AutoCompleteTextView textView){
		
	}
	public void afterTextChanged(Editable arg0) {
		// TODO Auto-generated method stub
		
	}
	public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
			int arg3) {
		// TODO Auto-generated method stub
		
	}
	public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
		// TODO Auto-generated method stub
		
	}
}


class SpaceTokenizer implements Tokenizer {
    public int findTokenStart(CharSequence text, int cursor) {
        int i = cursor;

        while (i > 0 && text.charAt(i - 1) != '\0') {
            i--;
        }
        while (i < cursor && text.charAt(i) == ' ') {
            i++;
        }

        return i;
    }

    public int findTokenEnd(CharSequence text, int cursor) {
        int i = cursor;
        int len = text.length();

        while (i < len) {
            if (text.charAt(i) == '\0') {
                return i;
            } else {
                i++;
            }
        }

        return len;
    }

    public CharSequence terminateToken(CharSequence text) {
        int i = text.length();

        while (i > 0 && text.charAt(i - 1) == ' ') {
            i--;
        }

        if (i > 0 && text.charAt(i - 1) == '\0') {
            return text;
        }
		return text;
    }
}
